package com.bestcem.xm.user.config.aspects;

import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.component.security.dto.TokenDTO;
import com.bestcem.xm.user.util.business.GroupLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;

/**
 * 实现组织层级锁的切面拦截
 *
 * @author qiongyu.cui <qiongyu.cui@idiaoyan.com>
 * @version v1.0
 * @date 2022/2/8 16:33
 */
@Aspect
@Component
@Slf4j
public class CheckGroupLockAspect {

    @Autowired
    private GroupLockUtil groupLockUtil;

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.bestcem.xm.user.annotations.CheckGroupLock)")
    public void pointCut() {
        // Do nothing because of pointcut expression
    }

    /**
     * 环绕通知拦截
     */
    @Around("pointCut()")
    public Object checkGroupLock(ProceedingJoinPoint pjp) {
        TokenDTO currentToken = SecurityContextHolder.getToken();
        if (null == currentToken) {
            log.error("未获取到当前的token信息");
            return XmResultJson.fail(ReqErrorCodeEnum.TOKEN_LOST);
        }
        String orgId = currentToken.getOrgId();
        if (groupLockUtil.getLockFlag(orgId)) {
            log.error("当前租户下的组织层级功能已被锁定，orgId：{}", orgId);
            return XmResultJson.fail(ResourceErrorCodeEnum.STATUS_CHANGED, "当前租户下组织层级功能被锁定！");
        }

        Object result;
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            log.error("组织层级业务异常", e);
            result = XmResultJson.fail(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "系统异常");
        }
        return result;
    }

}
